<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * @name Programs_management
 * @file programs_management.php
 * @author Zdeno kobezda
 * @version 1.0
 * @package CodeIgniter
 * @subpackage Controllers
 * @section POPIS
 * Predstavuje kontroler ktorý bude slúžiť na zobrazovanie informácii ohľadom programov,
 * ich filtrovanie a vyhľadávanie ako aj pridávanie, úpravu a mazanie.
 */
class Programs_managment extends MY_Controller {

    function __construct() {
        parent::__construct();

        $this->load->model(array('filesmodel', 'filesworktypemodel', 'filesclassroomsubjectmodel', 'fileslanguagemodel',
            'filesprogramosmodel', 'filesstudylevelmodel', 'worktypemodel', 'classroomsubjectmodel', 'languagemodel',
            'programosmodel', 'studylevelmodel', 'passwordmodel', 'ratingmodel', 'ratingrestrictsmodel'));
        $this->load->helper('file');
        $this->load->library('ftp');
    }
    
    private function prepareStructureTables() {
        $result = array();
        $result['work_type'] = $this->worktypemodel->getAll();
        $result['language'] = $this->languagemodel->getAll();
        $result['program_os'] = $this->programosmodel->getAll();
        $result['study_level'] = $this->studylevelmodel->getAll();
        $result['classroom_subject'] = $this->classroomsubjectmodel->getAll();
        return $result;
    }
    
    private function getSegments() {
        $segments = $this->uri->segment_array();
        $result = array();
        foreach($segments as $key => $val){
            if($key > 2){
                $result[] = $val;
            }
        }
        return $result;
    }
    
    private function getFilteredFiles($conditions, $orderBy, $pageNmbr)
    {
        $result = $this->filesmodel->getAllFiles($conditions, $orderBy, $pageNmbr);
        foreach($result as $item){
            $item->time = sqlTimestampToHuman($item->time, 'slovak');
            if(strlen($item->name) > 30)
                $item->comment = substr($item->comment, 0, 30)."...";
            if(strlen($item->comment) > 45)
                $item->comment = substr($item->comment, 0, 45)."...";
            $item->size = round($item->size / 1000, 1) . '&nbsp;kB';
        }
        return $result;
    }

    /**
     * 	Funkcia bude spracovávať údaje ohľadom filtrovania.
     */
    public function index() {
        $data['title'] = 'Filter programov | Archív výučbového softvéru';
        $data = array_merge($data, $this->prepareStructureTables());
        $data['page'] = 1;
        
        $conditions = array();
        $orderBy = array();
        
        $segments = $this->getSegments();
        foreach($segments as $seg){
            $arr = explode("-", $seg);
            if(is_array($arr) && count($arr) == 2){
                if($arr[0] == "page")
                    $data['page'] = $arr[1];
                else
                    $conditions[$arr[0]] = $arr[1];
            }
        }
        $files = $this->getFilteredFiles($conditions, $orderBy, $data['page']-1);
        $data['files'] = json_encode($files);
        $data['pageCount'] = $this->filesmodel->getPageCount($conditions);
        $this->load->view('templates/headers/header', $data, FALSE);
        $this->load->view('programs_managment/index', $data, FALSE);
        $this->load->view('templates/footers/footer', null, FALSE);
    }

    /**
     *  Funkcia ktorá bude slúžiť na spracovanie ajaxových dotazov ohľadom filtra programov.
     */
    public function filter() {
        if($this->input->is_ajax_request()){
            $formConditions = $this->input->post('cond');
            $conditions = array();
            $orderBy = array();
            foreach($formConditions as $key => $val){
                if($val != 0)
                    $conditions[$key] = $val;
            }
            $page = $this->input->post('page');
            $data = $this->getFilteredFiles($conditions, $orderBy, $page-1);
            if(count($conditions) > 0)
                $result['page'] = 1;
            else
                $result['page'] = $page;
            $result['pageCount'] = $this->filesmodel->getPageCount($conditions);
            $result['data'] = $data;
            echo json_encode($result);
        }
    }

    /**
     * Funkcia manažovania informácie ohľadom konkrétneho programu.
     * @param  [type] $id [Idcko programu v DB]
     */
    public function program($id) {
        if (!$this->filesmodel->idExists($id)) {
            redirect('/index/index', 'refresh');
        }
        $data['program_info'] = $this->filesmodel->read($id);
        $data['title'] = 'Detaily programu | '.$data['program_info']->name.' | Archív výučbového softvéru';

        $data['info_msg'] = ""; // bude bud "editted" alebo "created" alebo "", flag pre
        // informacie spojene s vytvorenim a editaciou programu
        
        //inf z akumulacnych tabuliek
        $data['workType'] = $this->filesworktypemodel->getAll_Akum($id, 'work_type');
        $data['classroomSubject'] = $this->filesclassroomsubjectmodel->getAll_Akum($id, 'classroom_subject');
        $data['language'] = $this->fileslanguagemodel->getAll_Akum($id, 'language');
        $data['programOs'] = $this->filesprogramosmodel->getAll_Akum($id, 'program_os');
        $data['studyLevel'] = $this->filesstudylevelmodel->getAll_Akum($id, 'study_level');

        $hodnotenie = $this->ratingmodel->getAll(null, null, array('fk_files' => $id,));
        $sum = 0;
        $poc = 0;
        foreach ($hodnotenie as $key) {
            $sum+=$key->value;
            $poc++;
        }
        if ($poc == 0) {
            $data['pi_rating'] = 0;
        } else {
            $data['pi_rating'] = $sum / $poc;
        }



        $this->load->view('templates/headers/header', $data, FALSE);
        $this->load->view('programs_managment/program', $data, FALSE);
        $this->load->view('templates/footers/footer', null, FALSE);
    }

    /**
     * Funkcia reprezentujúca proces vytvárania nového programu.
     */
    public function new_program() {
        //dorobit funkciu na listovanie lsll
        $data['maxUploadSize'] = 8192; // in Kb
        $data['title'] = 'Pridanie nového programu | Archív výučbového softvéru';
        $data['workType'] = $this->worktypemodel->getAll(null, null, null);
        $data['classroomSubject'] = $this->classroomsubjectmodel->getAll(null, null, null);
        $data['language'] = $this->languagemodel->getAll(null, null, null);
        $data['programOs'] = $this->programosmodel->getAll(null, null, null);
        $data['studyLevel'] = $this->studylevelmodel->getAll(null, null, null);


        $this->form_validation->set_rules('nazov', 'Názov', 'required');
        $this->form_validation->set_rules('heslo', 'Heslo pre upload', 'required');
        $this->form_validation->set_rules('comment', 'Opis', 'required');
        $this->form_validation->set_rules('autors', 'Autori', 'required');
        $this->form_validation->set_rules('requirements', 'Požiadavky', 'required'); 

     


        $this->form_validation->set_rules('workType', 'Typ práce', 'required');
        $this->form_validation->set_rules('classroomSubject', 'Učebný predmet', 'required');
        $this->form_validation->set_rules('language', 'Jazyk programu', 'required');
        $this->form_validation->set_rules('programOs', 'Operačný systém', 'required');
        $this->form_validation->set_rules('studyLevel', 'Stupeň štúdia', 'required');

    

        $config['upload_path'] = './public/upload/temp/';
        $config['allowed_types'] = 'zip';
        $config['max_size'] = $data['maxUploadSize'];
        $this->load->library('upload', $config);
 

        if ($this->form_validation->run() && $this->passwordmodel->check_password($this->input->post('heslo')) && $this->upload->do_upload() == true        ) {
            $data['upload_data'] = $this->upload->data();
            
               
            $o = new stdClass();
            $o->name = $this->input->post('nazov');
            $o->comment = $this->input->post('comment');
            $o->autors = $this->input->post('autors');
            $o->size = $_FILES['userfile']['size'];
            $o->requirements = $this->input->post('requirements');
            $id = $this->filesmodel->create($o);
            
            $path = './public/upload/'.$id.'';
            $file_string = read_file('./public/upload/temp/'.$data['upload_data']['file_name']);
            if(!is_dir($path)) //create the folder if it's not already exists
                {
                  mkdir($path,0755,TRUE);
                } 
            write_file('./public/upload/'.$id.'/'.$id.'.zip', $file_string);
   

            $dataUp['workType'] = $this->input->post('workType');
            $dataUp['classroomSubject'] = $this->input->post('classroomSubject');
            $dataUp['language'] = $this->input->post('language');
            $dataUp['programOs'] = $this->input->post('programOs');
            $dataUp['studyLevel'] = $this->input->post('studyLevel');

            $file_string = read_file('./public/upload/temp/'.$data['upload_data']['client_name']);
            $this->ftp->mkdir('/public/upload/'.$id.'/', DIR_WRITE_MODE);
            $this->ftp->chmod('/public/upload/'.$id.'/', DIR_WRITE_MODE);
            write_file('/public/upload/'.$id.'/'.$id.'.zip', $file_string);
            delete_files('./public/upload/temp/', TRUE);
            $this->createNew('filesworktypemodel', 'fk_work_type', $id, $dataUp['workType']);
            foreach ($dataUp['classroomSubject'] as $key) {

                $this->createNew('filesclassroomsubjectmodel', 'fk_classroom_subject', $id, $key);
            }
            foreach ($dataUp['language'] as $key) {
                $this->createNew('fileslanguagemodel', 'fk_language', $id, $key);
            }
            foreach ($dataUp['programOs'] as $key) {
                $this->createNew('filesprogramosmodel', 'fk_program_os', $id, $key);
            }
            foreach ($dataUp['studyLevel'] as $key) {
                $this->createNew('filesstudylevelmodel', 'fk_study_level', $id, $key);
            }

            redirect('programs_managment/program/' . $id, 'refresh');
        } else {

            $data['error'] = $this->upload->display_errors();
            // Vytvorenie informacii pre formulár 
          
            $data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
            
            

            $data['nazov'] = array('name' => 'nazov',
                'id' => 'nazov',
                'type' => 'text',
                'placeholder' => ' Názov vašeho programu',
                'value' => $this->form_validation->set_value('nazov'),
                'class' => 'input-xlarge',
            );

            $data['heslo'] = array('name' => 'heslo',
                'id' => 'heslo',
                'type' => 'password',
                'value' => $this->form_validation->set_value('heslo'),
                'class' => 'input-xlarge',
            );

            $data['comment'] = array('name' => 'comment',
                'id' => 'comment',
                'type' => 'text',
                'placeholder' => ' Informácie o programe',
                'value' => $this->form_validation->set_value('comment'),
                'rows' => 5,
                'cols' => 50,
                'class' => 'input-xlarge',
            );

            $data['autors'] = array('name' => 'autors',
                'id' => 'autors',
                'type' => 'text',
                'placeholder' => ' Autori programu',
                'value' => $this->form_validation->set_value('autors'),
                'class' => 'input-xlarge',
            );
            // text or textarea ?
            $data['requirements'] = array('name' => 'requirements',
                'id' => 'requirements',
                'type' => 'text',
                'placeholder' => ' Požiadavky pre používateľov tohto programu',
                'value' => $this->form_validation->set_value('requirements'),
                'rows' => 5,
                'cols' => 50,
                'class' => 'input-xlarge',
            );

            $this->load->view('templates/headers/header', $data, FALSE);
            $this->load->view('programs_managment/new_program', $data, FALSE);
            $this->load->view('templates/footers/footer', null, FALSE);
        }
    }

    /**
     * Editacia už existujúceho programu.
     * 
     * @param  [type] $id [Idcko programu v DB]
     */
    public function edit_program($id) {
        if (!$this->filesmodel->idExists($id)) {
            redirect('/index/index', 'refresh');
        }

        $data['title'] = 'Upravovanie programu | Archív výučbového softvéru';


        $data['prog_id'] = $id;

        $data['info_msg'] = ""; // bude bud "editted" alebo "created" alebo "", flag pre
        // informacie spojene s vztvorenim a editaciou programu
        $data['program_info'] = $this->filesmodel->read($id);
        //inf z akumulacnych tabuliek


        $data['workType'] = $this->worktypemodel->getAll(null, null, null);
        $data['classroomSubject'] = $this->classroomsubjectmodel->getAll(null, null, null);
        $data['language'] = $this->languagemodel->getAll(null, null, null);
        $data['programOs'] = $this->programosmodel->getAll(null, null, null);
        $data['studyLevel'] = $this->studylevelmodel->getAll(null, null, null);

        $this->addSelected('filesworktypemodel', $data['workType'], 'fk_work_Type', $id);
        $this->addSelected('filesclassroomsubjectmodel', $data['classroomSubject'], 'fk_classroom_subject', $id);
        $this->addSelected('fileslanguagemodel', $data['language'], 'fk_language', $id);
        $this->addSelected('filesprogramosmodel', $data['programOs'], 'fk_program_os', $id);
        $this->addSelected('filesstudylevelmodel', $data['studyLevel'], 'fk_study_level', $id);

        $this->form_validation->set_rules('nazov', 'Názov', 'required');
        $this->form_validation->set_rules('comment', 'Opis', 'required');
        $this->form_validation->set_rules('autors', 'Autori', 'required');
        $this->form_validation->set_rules('requirements', 'Požiadavky', 'required');
        $this->form_validation->set_rules('workType', 'Typ práce', 'required');
        $this->form_validation->set_rules('classroomSubject', 'Učebný predmet', 'required');
        $this->form_validation->set_rules('language', 'Jazyk programu', 'required');
        $this->form_validation->set_rules('programOs', 'Operačný systém', 'required');
        $this->form_validation->set_rules('studyLevel', 'Stupeň štúdia', 'required');

        if ($this->form_validation->run()) {
            $this->filesstudylevelmodel->deleteAll($id, 'fk_files');
            $this->filesworktypemodel->deleteAll($id, 'fk_files');
            $this->filesprogramosmodel->deleteAll($id, 'fk_files');
            $this->fileslanguagemodel->deleteAll($id, 'fk_files');
            $this->filesclassroomsubjectmodel->deleteAll($id, 'fk_files');

            $dataUp['workType'] = $this->input->post('workType');
            $dataUp['classroomSubject'] = $this->input->post('classroomSubject');
            $dataUp['language'] = $this->input->post('language');
            $dataUp['programOs'] = $this->input->post('programOs');
            $dataUp['studyLevel'] = $this->input->post('studyLevel');


            $this->createNew('filesworktypemodel', 'fk_work_type', $id, $dataUp['workType']);
            foreach ($dataUp['classroomSubject'] as $key) {

                $this->createNew('filesclassroomsubjectmodel', 'fk_classroom_subject', $id, $key);
            }
            foreach ($dataUp['language'] as $key) {
                $this->createNew('fileslanguagemodel', 'fk_language', $id, $key);
            }
            foreach ($dataUp['programOs'] as $key) {
                $this->createNew('filesprogramosmodel', 'fk_program_os', $id, $key);
            }
            foreach ($dataUp['studyLevel'] as $key) {
                $this->createNew('filesstudylevelmodel', 'fk_study_level', $id, $key);
            }

            $o = new stdClass();
            $o->id = $id;
            $o->name = $this->input->post('nazov');
            $o->comment = $this->input->post('comment');
            $o->autors = $this->input->post('autors');
            $o->requirements = $this->input->post('requirements');
            $this->filesmodel->update($o);

        
            
            $data['redirect_to'] = 'programs_managment/program/' . $id;
            $this->load->view('templates/headers/h_redirect_index', $data, FALSE);
            $this->load->view('programs_managment/form_states/edit_s', null, FALSE);
            $this->load->view('templates/footers/footer', null, FALSE);
        } else {


            // Vytvorenie informacii pre formulár 

            $data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');


            $data['nazov'] = array('name' => 'nazov',
                'id' => 'nazov',
                'type' => 'text',
                'placeholder' => ' Názov vašeho programu',
                'value' => $data['program_info']->name,
                'class' => 'input-large',
            );


            $data['comment'] = array('name' => 'comment',
                'id' => 'comment',
                'type' => 'text',
                'placeholder' => ' Informácie o programe',
                'value' => $data['program_info']->comment,
                'rows' => 5,
                'cols' => 50,
                'class' => 'input-large',
            );

            $data['autors'] = array('name' => 'autors',
                'id' => 'autors',
                'type' => 'text',
                'placeholder' => ' Autori programu',
                'value' => $data['program_info']->autors,
                'class' => 'input-large',
            );
            // text or textarea ?
            $data['requirements'] = array('name' => 'requirements',
                'id' => 'requirements',
                'type' => 'text',
                'placeholder' => ' Požiadavky pre používateľov tohto programu',
                'value' => $data['program_info']->requirements,
                'rows' => 5,
                'cols' => 50,
                'class' => 'input-large',
            );




            $this->load->view('templates/headers/header', $data, FALSE);
            $this->load->view('programs_managment/edit_program', $data, FALSE);
            $this->load->view('templates/footers/footer', null, FALSE);
        }
    }

    /**
     * Slúži na vymazanie už existujúceho programu
     * @param  [type] $id [Idcko programu v DB]
     */
    public function delete_program($id) {
        if (!$this->user->isLogged()) {
            redirect('/index/index', 'refresh');
        }
        if (!$this->filesmodel->idExists($id)) {
            redirect('/index/index', 'refresh');
        }

        $this->load->model('filesmodel');
        $this->load->model('filesworktypemodel');
        $this->load->model('filesclassroomsubjectmodel');
        $this->load->model('fileslanguagemodel');
        $this->load->model('filesprogramosmodel');
        $this->load->model('filesstudylevelmodel');
        $this->load->model('ratingmodel');


        $data['title'] = 'Zmazanie programu | Archív výučbového softvéru';
        $data['program_info'] = $this->filesmodel->read($id);
        $data['id'] = $id;


        $this->form_validation->set_rules('submit', 'Odpoved', 'required');


        if ($this->form_validation->run()) {

            if ($this->input->post('submit') == 'yes') {

                $this->filesstudylevelmodel->deleteAll($id, 'fk_files');
                $this->filesworktypemodel->deleteAll($id, 'fk_files');
                $this->filesprogramosmodel->deleteAll($id, 'fk_files');
                $this->fileslanguagemodel->deleteAll($id, 'fk_files');
                $this->filesclassroomsubjectmodel->delete(  array('fk_files' => $id , ) );
                $this->ratingrestrictsmodel->deleteAll($id,'fk_files');
                $this->ratingmodel->deleteAll($id, 'fk_files');
                $this->filesmodel->deleteAll($id, 'id');
                delete_files('./upload/'.$id.'/', TRUE);

                $data['redirect_to'] = '';
                $this->load->view('templates/headers/h_redirect_index', $data, FALSE);
                $this->load->view('programs_managment/form_states/delete_s', null, FALSE);
                $this->load->view('templates/footers/footer', null, FALSE);
            } else if ($this->input->post('submit') == 'no') {

                $data['redirect_to'] = '';
                $this->load->view('templates/headers/h_redirect_index', $data, FALSE);
                $this->load->view('programs_managment/form_states/delete_us', null, FALSE);
                $this->load->view('templates/footers/footer', null, FALSE);
            }
        } else {

            // Vytvorenie informacii pre formulár 
            $data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

            $data['submit_yes'] = array('name' => 'submit',
                'id' => 'submit_yes',
                'type' => 'submit',
                'value' => 'yes',
                'class'=> 'btn btn-info inpt',
            );

            $data['submit_no'] = array('name' => 'submit',
                'id' => 'submit_no',
                'type' => 'submit',
                'value' => 'no',
                'class'=> 'btn btn-info inpt',
            );

            $this->load->view('templates/headers/header', $data, FALSE);
            $this->load->view('programs_managment/delete_program', $data, FALSE);
            $this->load->view('templates/footers/footer', null, FALSE);
        }
    }

    /**
     * Spracováva AJAX pre hodnotenie programu.
     */
    public function rate_program() {
        $this->load->model('ratingmodel');
        $val = $this->input->post('ajaxRating');
        $id = $this->input->post('programId');
        if ($this->input->is_ajax_request()) {

            if ($this->checkUser($id)) {
                echo -1;
            } else {
                $o = new stdClass();
                $o->fk_files = $id;

                $o->value = $val;
                $this->ratingmodel->create($o);

                $hodnotenie = $this->ratingmodel->getAll(null, null, array('fk_files' => $id,));


                $sum = 0;
                $poc = 0;
                foreach ($hodnotenie as $key) {
                    $sum+=$key->value;
                    $poc++;
                }

                $this->fileUser($id);
                if ($poc == 0) {
                    echo 0;
                } else {
                    echo $sum / $poc;
                }
            }
        } else {
            
        }
    }

    private function checkUser($id) {
        return $this->ratingrestrictsmodel->check_restrict($this->input->ip_address(), $id);
    }

    private function fileUser($id) {
        $o = new stdClass();
        $o->ip_address = $this->input->ip_address();
        ;
        $o->fk_files = $id;

        $this->ratingrestrictsmodel->create($o);
    }

    private function addSelected($model, $what, $string, $id) {
        foreach ($what as $key) {
            if ($this->$model->hasAttribute($id, $string, $key->id)) {
                $key->selected = 1;
            } else {
                $key->selected = 0;
            }
        }
    }

    private function createNew($model, $string, $id, $val) {
        $o = new stdClass();
        $o->fk_files = $id;
        $o->$string = $val;
        $this->$model->create($o);
    }

}

/* End of file programs_managment.php */
/* Location: ./application/controllers/programs_managment.php */
